package cn.sinjet.model.carassist;
import com.mgroup.wazehelper.R;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import cn.sinjet.carassist.MainActivity;
import cn.sinjet.communication.bluetooth.BluetoothModel;
import cn.sinjet.model.carsystem.CarModel;

public class CarAssistService extends Service{
	 static final String tag = "CarAssistService";
	 public static final int MSG_AUTO_CONNECT_BT = 100;
	 public static final int MSG_SEND_INIT_OK = 101;
	 public static final int MSG_SEND_HEARTBEAT = 102;
	 public static final int MSG_NAVI_INFO = 103;
	 public static final int MSG_BT_CONNECTED = 104;
	 public static final int MSG_BT_DISCONNECTED = 105;
	 public static final int MSG_NOTIFY_NAVIGATING = 106;
	 public static final int MSG_SYNC_TIME = 107;
	 public static final int MSG_CONNECT_BAIDU = 108;
	 public static final int MSG_CHECK_NETWORK = 109;
	  HandlerThread mBackgroundThread = null;
	  BackgroundHandler mBackgroundHandler = null;

	  NaviInfoModule mNaviInfoModule = null;
	@Override
	public IBinder onBind(Intent intent) {
//		 TODO Auto-generated method stub
        Log.d(tag, "onBind flag:"+intent.getFlags());  //Init service after binded
//        mIsRunning = true;
		return mBinder;
	}
	private final IBinder mBinder = new LocalBinder();
	public class LocalBinder extends Binder {
		public CarAssistService getService() {
			return CarAssistService.this;
		}
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(tag,"onUnbind");
//		mIsRunning = false;
		return super.onUnbind(intent);
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(tag, "onCreate");
    	BluetoothModel.getInstance().initBTModel();//
    	mNaviInfoModule = new NaviInfoModule(getApplicationContext());
    	mBackgroundThread = new HandlerThread("ServiceBackgroundThread");
	    mBackgroundThread.start();
	    mBackgroundHandler = new BackgroundHandler((mBackgroundThread).getLooper());
	    mBackgroundHandler.sendEmptyMessage(MSG_AUTO_CONNECT_BT);
	}
 
	public Handler getMsgHandler(){
		return mBackgroundHandler;
	}
	
	class BackgroundHandler extends Handler{
		public BackgroundHandler(Looper looper) {
			// TODO Auto-generated constructor stub
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
//			super.handleMessage(msg);
			Log.i(tag, "service handle msg:"+msg.what);
			switch(msg.what){
			case MSG_AUTO_CONNECT_BT:
				handleAutoConnectBT();
//				mBackgroundHandler.sendEmptyMessageDelayed(MSG_CONNECT_BAIDU, 7000);
			   break;
			case MSG_NAVI_INFO:
				Bundle data = msg.getData();
				mNaviInfoModule.onNaviInfoMsg(data);
				break;
			case MSG_BT_CONNECTED:
				handleBTConnected();
				break;
			case MSG_BT_DISCONNECTED:
				handleBTDisconnected();
				break;
			case MSG_NOTIFY_NAVIGATING:
				mNaviInfoModule.notifyNavigatingState();
				this.sendEmptyMessageDelayed(MSG_NOTIFY_NAVIGATING, 3000);
				break;
			case MSG_SEND_HEARTBEAT:
				CarModel.getInstance().devModule.sendHeartbeat();
				this.sendEmptyMessageDelayed(MSG_SEND_HEARTBEAT, 3000);
				break;
			case MSG_SEND_INIT_OK:
				CarModel.getInstance().devModule.handleAppInitOK();
				break;
			case MSG_SYNC_TIME:
				CarModel.getInstance().devModule.syncTime();
				break;
			case MSG_CONNECT_BAIDU:
				CarModel.getInstance().devModule.connectBaiduNavi();
				this.sendEmptyMessageDelayed(MSG_CONNECT_BAIDU, 7000);
				break;
			case MSG_CHECK_NETWORK:
				AppModel.getInstance().checkNetworkStartLocation();
				break;
			}
		}
	}
	
	private void handleBTConnected() {
		// TODO Auto-generated method stub
        mBackgroundHandler.sendEmptyMessageDelayed(MSG_NOTIFY_NAVIGATING,3000);
        mBackgroundHandler.sendEmptyMessageDelayed(MSG_SEND_HEARTBEAT,3000);
        mBackgroundHandler.sendEmptyMessageDelayed(MSG_CONNECT_BAIDU, 7000);
	}
	
	private void handleBTDisconnected(){
		mBackgroundHandler.removeMessages(MSG_NOTIFY_NAVIGATING);
		mBackgroundHandler.removeMessages(MSG_SEND_HEARTBEAT);
		mBackgroundHandler.removeMessages(MSG_CONNECT_BAIDU);
	}
	
	void handleAutoConnectBT(){
		Log.d(tag,"Background thread auto connect");
       // if(AppModel.getInstance().getSettings().bAutoOpenBT){
      	  BluetoothModel.getInstance().tryToKeepConnected();
      //  }
        mBackgroundHandler.sendEmptyMessageDelayed(MSG_AUTO_CONNECT_BT, 10000);
	}
	
//	@SuppressWarnings("deprecation")
	@SuppressWarnings("deprecation")
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(tag,"onStartCommand flag:"+flags+" startId:"+startId);
		 Notification notification = new Notification(R.drawable.ic_launcher_sinjet,getString(R.string.app_name), System.currentTimeMillis());
//		 Intent appIntent = this.getPackageManager().getLaunchIntentForPackage(this.getPackageName());
		 notification.flags=Notification.FLAG_AUTO_CANCEL;  
	     Intent appIntent = new Intent(Intent.ACTION_MAIN);  
	     appIntent.setAction(Intent.ACTION_MAIN);  
	     appIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
	     appIntent.setComponent(new ComponentName(this.getPackageName(), MainActivity.class.getName()));
	     appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//关键的一步，设置启动模式  
		 //PendingIntent pendingintent = PendingIntent.getActivity(this, 0,new Intent(this, HudService.class), 0);
		 PendingIntent pendingintent = PendingIntent.getActivity(this, 0,appIntent, 0);
		 notification.setLatestEventInfo(this, "车载助手", "正在后台为您服务",pendingintent);
		 startForeground(0x111, notification);
		 return START_NOT_STICKY;//super.onStartCommand(intent, flags, startId);
	}
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(tag,"onDestory");
//		mIsRunning = false;
		if(mBackgroundThread != null && mBackgroundThread.isAlive())
			mBackgroundThread.stop();
		super.onDestroy();
	}

	public void onRecvMessage(Message msg) {
		// TODO Auto-generated method stub
		mBackgroundHandler.sendMessage(msg);
	}
	
}
